//
//  NavigationBar.swift
//  
//
//  Created by tank on 2021/12/16.
//

import Foundation
import UIKit
import SnapKit

open class NavigationBar: UIView {

    static let height: CGFloat = 44

    static let backButtonHeight: CGFloat = 30

    public let backButton: UIButton = {
        let button = UIButton()

        button.setTitle(IconFonts.arrowLeft, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.ex.iconFont(ofSize: 14)
        
        return button
    }()

    public let titleLabel: UILabel = {
        let label = UILabel()

        label.textColor = .white
        label.font = UIFont(name: "PingFangSC-Medium", size: 18)

        return label
    }()

    open override var intrinsicContentSize: CGSize {
        return CGSize(width: UIWindow.ex.key?.frame.width ?? 0,
                      height: UIApplication.shared.statusBarFrame.height + NavigationBar.height)
    }

    public init() {
        super.init(frame: CGRect.zero)

        addSubview(backButton)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        backButton.addGestureRecognizer(tap)
        
        addSubview(titleLabel)
    }

    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func updateConstraints() {
        super.updateConstraints()
        
        backButton.snp.updateConstraints { make in
            make.width.height.equalTo(30)
            make.centerY.equalTo(UIApplication.shared.statusBarFrame.height + NavigationBar.height / 2)
            make.left.equalToSuperview().offset(6)
        }

        titleLabel.snp.updateConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton.snp.centerY)
        }
    }
    
    @objc func handleTap(_ sender: UITapGestureRecognizer) {
        ex.viewController?.navigationController?.popViewController(animated: true)
    }
}
